// pages/chapterPractice/chapterPractice.js
// const API_BASE = 'http://172.20.10.14:8001';
const API_BASE       = 'https://tihaidengta.xyz';
const STORAGE_KEY    = 'chapter_practice_progress';
const FAVORITE_KEY   = 'favoriteQuestions';
const WRONG_KEY      = 'wrongQuestions';

/**
 * 将题目 q（包含 uniqId, content, subjectType, optionsArray, answer, explanation）存入“错题本”
 * 已存在则跳过
 */
function saveWrongQuestion(q) {
  const list = wx.getStorageSync(WRONG_KEY) || [];
  if (!list.find(item => item.uniqId === q.uniqId)) {
    list.push({
      uniqId:       q.uniqId,
      content:      q.content,
      subjectType:  q.subjectType,
      optionsArray: q.optionsArray || [],
      answer:       q.answer,
      explanation:  q.explanation || ''
    });
    wx.setStorageSync(WRONG_KEY, list);
  }
}

Page({
  data: {
    isDarkMode: false,
    showThemePanel: false,
    userAnswers: {}, // ✅ 用来存每题的答题记录
    chapterCode: '',
    bankId: '',

    questions: [],            // 题目列表
    currentIndex: 0,          // 当前题目
    userAnswer: '',           // 文本题输入
    answeredQuestions: [],     // 已答题索引
    showResult: false,        // 显示对／错
    correctCount: 0,          // 已答对数量

    isLoading: false,
    slideTransform: '',
    startTouchX: 0,
    endTouchX: 0
  },

  onLoad(options) {
    // 深色模式
    const isDark = wx.getStorageSync('isDarkMode') || false;
    this.setData({ isDarkMode: isDark });

    const { chapterCode, bankId } = options;
    this.setData({ chapterCode, bankId });

    // 恢复进度或拉题
    const cache = wx.getStorageSync(STORAGE_KEY);
    if (cache 
        && cache.chapterCode === chapterCode 
        && Array.isArray(cache.questions)) 
    {
      wx.showModal({
        title: '检测到未完成练习',
        content: '是否继续上次练习？',
        confirmText: '继续',
        cancelText: '重做',
        success: res => {
          if (res.confirm) {
            this.setData(cache);
            return;
          }
          this.clearCache();
          this.fetchQuestions();
        }
      });
    } else {
      this.fetchQuestions();
    }
  },

  // 拉取题目
  fetchQuestions() {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });
    wx.showLoading({ title: '加载题目...', mask: true });

    // 先取收藏列表
    const favs = wx.getStorageSync(FAVORITE_KEY) || [];

    wx.request({
      url: `${API_BASE}/eduservice/subject/subjectQuestionList/${this.data.chapterCode}/1/300`,
      method: 'POST',
      success: res => {
        const raw = res.data.data?.list || [];
        const questions = raw.map((item, i) => {
          // 构造选项
          const opts = [];
          if (item.subjectType === 1) {
            ['a','b','c','d'].forEach((k, idx) => {
              if (item[k]) opts.push({
                key: String.fromCharCode(65 + idx),
                text: item[k],
                statusClass: ''
              });
            });
          }
          // 是否已收藏
          const collected = favs.some(f => f.uniqId === item.uniqId);
          return {
            uniqId:       item.uniqId || i,
            content:      item.title,
            subjectType:  item.subjectType,
            answer:       item.answer,
            explanation:  item.subjectNote || '',
            optionsArray: opts,
            userAnswer:   '',
            collected
          };
        });
        this.setData({
          questions,
          currentIndex: 0,
          userAnswer: '',
          answeredQuestions: [],
          showResult: false,
          correctCount: 0
        });
      },
      fail: () => wx.showToast({ title: '题目加载失败', icon: 'none' }),
      complete: () => {
        wx.hideLoading();
        this.setData({ isLoading: false });
      }
    });
  },

  /********* 收藏逻辑 *********/
  toggleCollect() {
    const idx = this.data.currentIndex;
    const qs  = this.data.questions;
    const q   = qs[idx];
    q.collected = !q.collected;
    qs[idx] = q;
    this.setData({ questions: qs });

    let favs = wx.getStorageSync(FAVORITE_KEY) || [];
    if (q.collected) {
      favs.push(q);
      wx.showToast({ title: '已加入收藏', icon: 'none' });
    } else {
      favs = favs.filter(x => x.uniqId !== q.uniqId);
      wx.showToast({ title: '已取消收藏', icon: 'none' });
    }
    wx.setStorageSync(FAVORITE_KEY, favs);
  },
  /****************************/

  // 单选题选中
  onSelect(e) {
    const uniqId = e.currentTarget.dataset.uniqid;
    const key    = e.currentTarget.dataset.key;
    const idx    = this.data.questions.findIndex(q => q.uniqId === uniqId);
    if (idx < 0) return;
    const q = this.data.questions[idx];
    if (q.userAnswer) return;
// ✅ 新增：记录答题到 userAnswers 中
const ua = this.data.userAnswers;
ua[idx] = key;
    // 标记答案
    q.userAnswer = key;
    q.optionsArray = q.optionsArray.map(opt => {
      let cls = '';
      if (opt.key === q.answer) cls = 'correct';
      else if (opt.key === key)  cls = 'wrong';
      return { ...opt, statusClass: cls };
    });

    const correct = key === q.answer;
    if (!correct) {
      saveWrongQuestion(q);
    } else {
      this.setData({ correctCount: this.data.correctCount + 1 });
    }

    const ans = [...new Set([...this.data.answeredQuestions, idx])];
    this.setData({
      questions: this.data.questions,
      showResult: true,
      answeredQuestions: ans,
      userAnswers: ua // ✅ 更新 userAnswers 传给组件
    });

    this.saveProgress();
    if (correct) setTimeout(() => this.nextQuestion(), 800);
  },

  // 文本题输入
  onInputAnswer(e) {
    this.setData({ userAnswer: e.detail.value });
  },
  // 文本题提交
  submitTextAnswer() {
    const ua = this.data.userAnswers;
ua[idx] = val;
    const idx = this.data.currentIndex;
    const q   = this.data.questions[idx];
    if (q.userAnswer) return;

    const val = this.data.userAnswer.trim();
    q.userAnswer = val;
    const correct = val === (q.answer || '').trim();
    if (!correct) {
      saveWrongQuestion(q);
    } else {
      this.setData({ correctCount: this.data.correctCount + 1 });
    }

    const ans = [...new Set([...this.data.answeredQuestions, idx])];
    this.setData({
      questions: this.data.questions,
      showResult: true,
      answeredQuestions: ans,
      userAnswers: ua // ✅ 添加这句
    });
    this.saveProgress();
    if (correct) setTimeout(() => this.nextQuestion(), 800);
  },

  // 题号导航回调
  changeQuestion(e) {
    const idx = e.detail.index;
    this.setData({
      currentIndex: idx,
      showResult: false,
      userAnswer: ''
    });
  },

  // 上一题
  prevQuestion() {
    if (this.data.currentIndex > 0) {
      const ni = this.data.currentIndex - 1;
      this.setData({
        currentIndex: ni,
        userAnswer: this.data.questions[ni].userAnswer,
        showResult: false
      });
    }
  },
  // 下一题
  nextQuestion() {
    const ni = this.data.currentIndex + 1;
    if (ni < this.data.questions.length) {
      this.setData({
        currentIndex: ni,
        userAnswer: this.data.questions[ni].userAnswer,
        showResult: false
      });
    } else {
      this.finishPractice();
    }
  },

  // 完成练习
  finishPractice() {
    this.clearCache();
    wx.showModal({
      title: '练习完成',
      content: `共 ${this.data.questions.length} 题，答对 ${this.data.correctCount} 题`,
      showCancel: false,
      success: () => wx.navigateBack()
    });
  },

  // 存储进度
  saveProgress() {
    const { questions, currentIndex, correctCount, answeredQuestions, chapterCode } = this.data;
    wx.setStorageSync(STORAGE_KEY, { questions, currentIndex, correctCount, answeredQuestions, chapterCode });
  },
  clearCache() {
    wx.removeStorageSync(STORAGE_KEY);
  },

  /****** 触摸滑动 换题 ******/
  touchStart(e) {
    this.setData({ startTouchX: e.changedTouches[0].pageX });
  },
  touchMove(e) {
    const moveX = e.changedTouches[0].pageX - this.data.startTouchX;
    const max   = 100;
    const limit = Math.min(Math.max(moveX, -max), max);
    this.setData({ slideTransform: `translateX(${limit}px)` });
  },
  touchEnd(e) {
    this.setData({ endTouchX: e.changedTouches[0].pageX });
    const { startTouchX, endTouchX } = this.data;
    if (endTouchX - startTouchX > 50) this.prevQuestion();
    else if (startTouchX - endTouchX > 50) this.nextQuestion();
  },
  /****************************/

  // 深色模式 / 题号卡
  toggleThemePanel() {
    this.setData({ showThemePanel: !this.data.showThemePanel });
  },
  toggleDarkMode(e) {
    // console.log('⚡️ toggleDarkMode called, e.detail:', e.detail);
    const isDark = e.detail.value;
    wx.setStorageSync('isDarkMode', isDark);
    this.setData({ isDarkMode: isDark });
  },
  // toggleNavigator() {
  //   this.setData({ showNavigator: !this.data.showNavigator });
  // }
});
